//
//  UserAccount.swift
//  weibo10
//
//  Created by 周荣硕 on 16/1/11.
//  Copyright © 2016年 grgbanking. All rights reserved.
//

import UIKit

//用户账户模型
class UserAccount: NSObject, NSCoding {

    //用于调用access_token, 用于获取授权后的 accessToken
    var access_token: String?
    //access_token的生命周期 ，单位是秒数
//    var expires_in: NSTimeInterval = 0
    /// 一旦从服务器获得过期的时间，立刻计算精准的时间
    var expires_in: NSTimeInterval = 0{
    
        didSet{
        
            //计算过期日期
            expiresDate = NSDate(timeIntervalSinceNow: expires_in)
        }
        
    }
    /// 过期日期
    var expiresDate: NSDate?
    
    //当前授权用户的UID
    var uid: String?
    var screen_name: String?
    var avatar_large:String?
    
    init(dict:[String:AnyObject]){
    
        super.init()
        
        setValuesForKeysWithDictionary(dict)
        
//        expires_in .description
    }
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
        
    }
    
    override var description: String{
        
        let keys = ["access_token", "expires_in","expiresDate", "uid","avatar_large","screen_name"]
    
        return dictionaryWithValuesForKeys(keys).description
    }
    
    //MARK:--保存当前对象
//    func saveUserAccount(){
//        //1.保存路径
//        var path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last!
//        // 2. 从 Xcode 7 beta 5 开始 stringByAppendingPathComponent 转为 NSString 特有
//        path = (path as NSString).stringByAppendingPathComponent("account.plist")
//        
//        //实际开发中，一定要确认文件真的保存了
//        print(path)
//        
//        //3.归档保存
//        NSKeyedArchiver.archiveRootObject(self, toFile: path)
//        
//    }
    
    ///  归档 - 在把当前对象 保存到磁盘前,将对象编码成二进制 --跟网络的序列化概念很像
    ///
    ///  - parameter aCoder: 编码器
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(access_token,forKey: "access_token")
        aCoder.encodeObject(expiresDate, forKey: "expiresDate")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(screen_name, forKey: "screen_name")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")

    }
    
    ///  解档-- 从磁盘加载二进制文件 转换成对象时调用 跟网络的反序列化很像
    ///
    ///  - parameter aDecoder: 解码器
    ///
    ///  - returns: 当前对象
    required init?(coder aDecoder: NSCoder) {
        
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        expiresDate = aDecoder.decodeObjectForKey("expiresDate") as? NSDate
        uid = aDecoder.decodeObjectForKey("uid") as? String
        screen_name = aDecoder.decodeObjectForKey("screen_name") as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String

        
        
    }
}
